//
//  DDWriteBtnViewController.swift
//  swift微博
//
//  Created by whitcast on 16/7/18.
//  Copyright © 2016年 whitcast. All rights reserved.
//

import UIKit
import SVProgressHUD

class DDWriteBtnViewController: UIViewController {
    
    //MARK:--保存相册中获取的图片
     var img: UIImage?{
        didSet{
            //数据源
            txtView.pictureView.infosArr.append(img!)
        }
    }
    
    ////MARK:--导航栏中间的titleVeiw
    lazy var titleView: UILabel = {
        
        let lab = UILabel()
        
        lab.textColor = UIColor.darkGrayColor()
        
        lab.font = UIFont.systemFontOfSize(14)
        
        lab.numberOfLines = 0  //不换行,无法显示副文本
        
        lab.textAlignment = NSTextAlignment.Center
        
        if let name = DDUserAccountModel.getDataFormLocal()?.screen_name {
            
            let title = "写微博\n\(name)"
            //副标题
            let attributeStr = NSMutableAttributedString(string: title)
            //副标题的位置
            let range = (title as NSString).rangeOfString(name)
            
            attributeStr.addAttributes([NSForegroundColorAttributeName: UIColor.lightGrayColor(),NSFontAttributeName: UIFont.systemFontOfSize(12)], range: range)
            
            lab.attributedText = attributeStr
        }else {
            lab.text = "发微博"
        }
        lab.sizeToFit()
        
        return lab
    }()
    
    ////MARK:--导航栏右边按钮
    lazy var rightWriteBtn: UIButton = {
        
        let btn = UIButton()
        
        btn.setTitle("发送", forState: .Normal)
        btn.titleLabel?.font = UIFont.boldSystemFontOfSize(15)
        
        btn.setTitleColor(UIColor.whiteColor(), forState: .Normal)
        btn.setTitleColor(UIColor.blackColor(), forState: .Disabled)
        btn.setBackgroundImage(UIImage(named: "common_button_orange"), forState: UIControlState.Normal)
        btn.setBackgroundImage(UIImage(named: "common_button_orange_highlighted"), forState: UIControlState.Highlighted)
        
        btn.setBackgroundImage(UIImage(named: "common_button_white_disable"), forState: UIControlState.Disabled)
        
        btn.addTarget(self, action: "send", forControlEvents: UIControlEvents.TouchUpInside)
        
        btn.size = CGSizeMake(45, 30)
        
        return btn
    }()
    
    ////MARK:--视图中间的textView
    private lazy var txtView: DDCustomTextView = {
        let view = DDCustomTextView()
        
        view.delegate = self
        //开启弹簧效果
        //开启textView的弹簧效果才能使用UIScollView的代理事件
        view.alwaysBounceVertical = true
        
        return view
        
    }()
    //inputView视图
    private lazy var keyBoard: DDEmojiVeiw = {
    
        let view = DDEmojiVeiw()
        
        view.frame.size = CGSizeMake(self.txtView.frame.size.width,300)
    
        return view
    }()
    ////MARK:--底部的toolbar视图
    private lazy var toolbarView: DDCustomToolBar = {
        
        let view = DDCustomToolBar()
        //底部视图toolbar的闭包回调
        view.buttonClickClourse = {[weak self] (btn: UIButton)-> () in
            
            self?.doSomeThingWithClourse(btn)
        }
        
        return view
        
    }()
    ////MARK:--根据toolbar的回调,进行的事件
    private func doSomeThingWithClourse(btn: UIButton){
        print("根据toolbar的回调,进行的事件")
        let type = btnType(rawValue: btn.tag)
        if type == .pic {
            //跳转相册
            let pictureVC = UIImagePickerController()
            
            pictureVC.delegate = self
            
            pictureVC.sourceType = .SavedPhotosAlbum
            
            presentViewController(pictureVC, animated: true, completion: nil)
        }else if type == .emoji {
            //表情键盘 
            txtView.inputView = keyBoard
            
            txtView.reloadInputViews()
           
            
            
        }
        
        
            
}
       
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        //背景颜色
        view.backgroundColor = UIColor.whiteColor()
        //设置UI
        setNavUpUI()
        setupUI()
        //监听系统键盘的通知,调整toolbar的位置
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyBoardframe:", name: UIKeyboardWillChangeFrameNotification, object: nil)
        

    }
    ////MARK:--监听系统键盘的通知
    @objc private func keyBoardframe(noti: NSNotification){
        //键盘改变的frame值
        let frame1 = (noti.userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue()
        //动画时间
        let animationTime = (noti.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! NSNumber).doubleValue
        //跟新toolbar 的底部约束
        toolbarView.snp_updateConstraints { (make) -> Void in
            make.bottom.equalTo(self.view).offset(frame1.origin.y - self.view.height)
        }
        //动画
        UIView.animateWithDuration(animationTime) { () -> Void in
            self.view.layoutIfNeeded()
        }
    }
    
    ////MARK:--设置Nav的UI,添加控件,设置约束
    private func setNavUpUI() {
        //取消按钮
        navigationItem.leftBarButtonItem = UIBarButtonItem.init(title: "取消", style: .Plain, target: self, action: "cancel")
        //右边写微博按钮
        navigationItem.rightBarButtonItem = UIBarButtonItem.init(customView: rightWriteBtn)
        //禁用按钮
        navigationItem.rightBarButtonItem?.enabled = false
        //中间的tiitleView
        navigationItem.titleView = titleView
        
    }
    ////MARK:--设置ui
    private func setupUI(){
        //添加txtView
        view.addSubview(txtView)
        view.addSubview(toolbarView)
        
        txtView.pictureView.addBtnClourseOfView = {[weak self] infosArr in
            //跳转相册
            let pictureVC = UIImagePickerController()
            
            pictureVC.delegate = self
            
            pictureVC.sourceType = .SavedPhotosAlbum
            
            self!.presentViewController(pictureVC, animated: true, completion: nil)
      
}
        //约束
        txtView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(self.view.snp_edges).offset(UIEdgeInsetsZero)
        }
        toolbarView.snp_makeConstraints { (make) -> Void in
            make.bottom.equalTo(self.view)
            make.leading.equalTo(self.view)
            make.trailing.equalTo(self.view)
            make.height.equalTo(30)
        }
    }
}

//MARK: --相册的代理事件
extension DDWriteBtnViewController: UIImagePickerControllerDelegate,UINavigationControllerDelegate{
    
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
        print(editingInfo)
          //压缩图片
        img = scaleImageWithScale(200, img: image)
        
        dismissViewControllerAnimated(true, completion: nil)
   
    }
    
        func imagePickerControllerDidCancel(picker: UIImagePickerController){
        print(picker)
        //销毁控制器
        picker.dismissViewControllerAnimated(true) { () -> Void in

        }
    }
    
    //MARK : -- 处理获取的图片,将图片压缩
    private func scaleImageWithScale(width: CGFloat,img: UIImage)->UIImage{
        //压缩后的大小
        let scaleHgeiht = (width / img.size.width) * img.size.height
        
        let scaleSize = CGSizeMake(width, scaleHgeiht)
        //开启图片上下文
        UIGraphicsBeginImageContext(scaleSize)
        
        img.drawInRect(CGRect(origin: CGPointZero, size: scaleSize))
        //获取绘制的图片
       let image = UIGraphicsGetImageFromCurrentImageContext()
        //关闭上下文
        UIGraphicsEndImageContext()
        
        return image
        
    }

    
}

//MARK:--导航栏的按钮
extension DDWriteBtnViewController{
    //取消按钮的点击事件
    @objc private func cancel(){
        //收回键盘
        self.view.endEditing(true)
        //返回上一级控制器
        //关闭下一个控制器

        dismissViewControllerAnimated(false, completion: nil)
    
        NSNotificationCenter.defaultCenter().postNotificationName("closeWriteBtnVC", object: nil)
           
        }
    //右边发送按钮
    @objc private func send(){
        
        print("点击了发送按钮")
        self.view.endEditing(true)
        if txtView.pictureView.infosArr.count == 0 {
            //上传文字
            DDHTTPSessionManagerTool.shardTool.sendText(txtView.text!) { (response, error) -> () in
                if error != nil {
                    print(error)
                    SVProgressHUD.showErrorWithStatus("请求失败")
                }else{
                    SVProgressHUD.showSuccessWithStatus("请求成功")
                }
            }

        }else {
            //上传图片
            let image = txtView.pictureView.infosArr.first
            
            DDHTTPSessionManagerTool.shardTool.sendPicAndText(txtView.text!, image: image!, callBack: { (response, error) -> () in
                if error != nil {
                    print(error)
                    SVProgressHUD.showErrorWithStatus("请求失败")
                }else{
                    SVProgressHUD.showSuccessWithStatus("请求成功")
                }
            })
           
        }
    }
}

// MARK:--textView的代理事件
extension DDWriteBtnViewController: UITextViewDelegate{
    //收回键盘 textView遵守了UIScrol的代理方法
    func scrollViewWillBeginDragging(scrollView: UIScrollView){
        
        self.view.endEditing(true)
    }
    
    //监听文本的改变
    func textViewDidChange(textView: UITextView){
        
        navigationItem.rightBarButtonItem?.enabled = txtView.hasText()
    }
    
}